export default {
  wxLogin, //获取code
  getUserInfo, //获取用户信息
  login, //授权登录
}

const app = getApp();

/**
 * 获取code 
 * @params wrongs Number 请求次数[失败时累加]
 */
function wxLogin(wrongs = 0) {
  const that = this;
  // 需要先调用login再调用getUserInfo，不然会概率性获取用户失败
  wx.login({
    success: function (res) {
      const code = res.code;
      console.log("获取code成功", code);
      that.code = code;
      that.getUserInfo();
    },
    fail: function () {
      if (wrongs == 2) {
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: '当前获取code多次失败，请联系平台管理员',
        })
        return false;
      }
      that.wxLogin(wrongs++);
    }
  })
}

/**
 * 自动获取用户信息，已授权可以
 */
function getUserInfo() {
  const that = this;
  wx.getUserInfo({
    complete(res) {
      console.log("获取用户信息", res);
      let userInfo = {};
      if (res.encryptedData) {
        userInfo = res;
      }
      that.login(userInfo);
    }
  })
}

/**
 * 服务器登录接口
 * @params 用户密钥信息
 */
function login(userInfo = {}) {
  const that = this;
  const code = that.code;
  const reqData = {
    wxCode: code,
    secrectIv: userInfo.iv || "",
    userSecretData: userInfo.encryptedData || "",
    shareUserId: app.shareUserId,
    shareActivityUuid: app.shareActivityUuid,
  }

  app.middleware.requestAjax({
    serAddr: app.serAddrs.login,
    data: reqData,
    cancelToast: true,
    success: function (res) {
      // console.log("success获取服务器用户", res);
      try {
        if (userInfo.encryptedData) res.data.noLogin = false;
        app.userInfo = Object.assign({}, app.userInfo || {}, res.data || {});
        // console.log("app.userInfo", app.userInfo)
      } catch (e) {
        console.error("问题错", e);
      }
    },
    complete:function(res){
      console.log("complete获取服务器用户", res);
      if (that.userCallback) that.userCallback(res);
    }
  })
}